package vip.liux.contracts.infrastructure.messaging.handlers;

import jakarta.annotation.PostConstruct;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import vip.liux.contracts.shared.enums.messing.ChannelType;

import java.util.List;

public class MessageHandlerFactory implements BeanFactoryAware {

    private static List<AbstractMessageHandler> handlers;
    private BeanFactory beanFactory;

    /**
     * 根据 ChannelType 获取支持的 MessageHandler。
     *
     * @param channelType 通道类型
     * @return 支持该通道类型的 MessageHandler
     * @throws IllegalArgumentException 如果没有找到支持的处理器
     */
    public static AbstractMessageHandler build(ChannelType channelType) {
        return handlers.stream()
                .filter(handler -> handler.supports(channelType))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("未找到支持通道类型 " + channelType.getDesc() + " 的消息处理器"));
    }

    @PostConstruct
    public void init() {
        // 从 BeanFinder 中获取所有 AbstractMessageHandler 的实现
        handlers = this.beanFactory.getBeanProvider(AbstractMessageHandler.class).stream().toList();
    }

    @Override
    public void setBeanFactory(@NotNull BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}